package com.zane.service.auth.impl;

import com.zane.common.security.MyUserDetails;
import com.zane.common.utils.JwtUtil;
import com.zane.dto.LoginRequest;
import com.zane.service.auth.AuthService;
import com.zane.vo.LoginResponse;
import com.zane.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    private final JwtUtil jwtUtil;
    private final PasswordEncoder PasswordEncoder;
    private final AuthenticationManager authenticationManager;


    @Autowired
    public AuthServiceImpl(JwtUtil jwtUtil, org.springframework.security.crypto.password.PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager) {
        this.jwtUtil = jwtUtil;
        PasswordEncoder = passwordEncoder;
        this.authenticationManager = authenticationManager;
    }

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 1. 用authentication验证用户身份
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                loginRequest.getUsername(), loginRequest.getPassword()
        ));
        log.info("用户身份验证成功：{}",authenticate);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        // 2. 验证成功后，创建token
        MyUserDetails userDetails = (MyUserDetails) authenticate.getPrincipal();
        log.info("用户信息：{}",userDetails);
        String token = jwtUtil.generateTokenByUserDetails(userDetails);
        log.info("用户生成token成功：{}",token);

        return LoginResponse.builder()
                .accessToken(token)
                .expire(jwtUtil.getExpire())
                .roleName(userDetails.getRoleName())
                .username(userDetails.getUsername()).build();
    }

    @Override
    public RegisterVO register(LoginRequest loginRequest) {
        return null;
    }
}
